﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace RpgMVX_SavesManager
{
    static class GetSetSettings
    {
        private static string ininame;
        private static string sec = "MainSetting";
        private static bool initialized = false;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string value, string filepath);
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retvalue, int size, string filepath);

        public static void initalize(string name)
        {
            if (initialized) return;
            initialized = true;
            ininame = name;
            if (!File.Exists(ininame)){
                new FileStream(ininame, FileMode.OpenOrCreate).Close();
                reset();
                var tmp = sec;
                sec = "RecentPath";
                for (int i = 1; i < 6; i++)
                {
                    setConfig("path" + i, string.Empty);
                }
                sec = tmp;
            }
            else
            {
                refresh();
                calibrate();
            }
        }

        public static void reset()
        {
            Setting.autoBackupG = true;
            Setting.selfNamingG = false;
            Setting.popupG = false;
            Setting.namingPatternG = "";
            Setting.bGameFolderG = false;
            Setting.bFolderG = "";
            calibrate();
            save(new SettingPack());
            refresh();
        }

        private static void refresh()
        {
            foreach (string item in Setting.nameList)
            {
                switch (item)
                {
                    case "autoBackup":
                        Setting.autoBackupG = Utils.stringToBool(getConfig(item));
                        break;
                    case "autoNaming":
                        Setting.selfNamingG = Utils.stringToBool(getConfig(item));
                        break;
                    case "popup":
                        Setting.popupG = Utils.stringToBool(getConfig(item));
                        break;
                    case "namingPattern":
                        Setting.namingPatternG = getConfig(item);
                        break;
                    case "backupInGameFolder":
                        Setting.bGameFolderG = Utils.stringToBool(getConfig(item));
                        break;
                    case "backupFolder":
                        Setting.bFolderG = getConfig(item);
                        break;
                    case "gameFolder":
                        Setting.gameFolder = getConfig(item);
                        break;
                    default:
                        continue;
                }
            }
        }

        private static void refresh(SettingPack sp)
        {
            Setting.autoBackupG = sp.autoBackup;
            Setting.selfNamingG = sp.selfNaming;
            Setting.popupG = sp.popup;
            Setting.namingPatternG = sp.namingPattern;
            Setting.bGameFolderG = sp.bGameFolder;
            Setting.bFolderG = sp.bFolder;
        }

        public static void savePath(string path)
        {
            var tmp = sec;
            sec = "RecentPath";
            List<string> ls = new List<string>();
            for (int i = 1; i < 6; i++)
            {
                var x = getConfig("path" + i);
                if (x == path) return;
                if (Utils.isValidString(x)) {
                    ls.Add(x);
                    continue;
                }
                setConfig("path" + i, path);
                sec = tmp;
                return;
            }
            ls.Reverse();
            ls.RemoveAt(0);
            ls.Add(path);
            ls.Reverse();
            int ia = 1;
            foreach (var il in ls)
            {
                setConfig("path" + ia, il);
                ia++;
            }
            sec = tmp;
        }

        public static void save(SettingPack sp)
        {
            refresh(sp);
            calibrate();
            foreach (string item in Setting.nameList)
            {
                switch (item)
                {
                    case "autoBackup":
                        setConfig(item, Utils.boolToString(Setting.autoBackupG));
                        break;
                    case "autoNaming":
                        setConfig(item, Utils.boolToString(Setting.selfNamingG));
                        break;
                    case "popup":
                        setConfig(item, Utils.boolToString(Setting.popupG));
                        break;
                    case "namingPattern":
                        setConfig(item, Setting.namingPatternG);
                        break;
                    case "backupInGameFolder":
                        setConfig(item, Utils.boolToString(Setting.bGameFolderG));
                        break;
                    case "backupFolder":
                        setConfig(item, Setting.bFolderG);
                        break;
                    case "gameFolder":
                        setConfig(item, Setting.gameFolder);
                        break;
                    default:
                        continue;
                }
            }
        }

        private static void calibrate()
        {
            //TODO: Refresh() --> nameingPattern = selfNaming ? "" : "[Filename] _ [Data] _ [X]" etc.
            Setting.namingPatternG = Setting.selfNamingG ? Setting.namingPatternG : !Utils.isValidString(Setting.namingPatternG) ? "[文件名]_[时间:年/月/日_时:分:秒:毫秒_时间截]_[编号].[后缀]_backup" : Setting.namingPatternG;
            Setting.bFolderG = Setting.bGameFolderG ? Setting.bFolderG : !Utils.isValidString(Setting.bFolderG) ? AppDomain.CurrentDomain.BaseDirectory + "Backups" : Setting.namingPatternG;
        }

        private static void setConfig(string key, string value)
        {
            WritePrivateProfileString(sec, key, value, ininame);
        }

        private static string getConfig(string key)
        {
            StringBuilder stb = new StringBuilder(255);
            GetPrivateProfileString(sec, key, "", stb, 255, ininame);
            return stb.ToString().Trim();
        }
    }

    public class IGameConfig
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string value, string filepath);
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retvalue, int size, string filepath);
        private string file;
        private bool isValid;
        public IGameConfig(string file)
        {
            isValid = Utils.isValidPath(file) && new FileInfo(file).Extension == "ini";
            this.file = Utils.isValidPath(file) && isValid ? file : string.Empty;
        }

        public string getTitle()
        {
            return isValid ? getConfig("Title") : string.Empty;
        }

        public string getLib()
        {
            return isValid ? getConfig("Library") : string.Empty;
        }

        private void setConfig(string key, string value)
        {
            WritePrivateProfileString("Game", key, value, file);
        }

        private string getConfig(string key)
        {
            StringBuilder stb = new StringBuilder(255);
            GetPrivateProfileString("Game", key, "", stb, 255, file);
            return stb.ToString().Trim();
        }
    }

    public static class Setting
    {
        public static bool autoBackupG = true;
        public static bool selfNamingG = false;
        public static bool popupG = false;
        public static string namingPatternG = "";
        public static bool bGameFolderG = false;
        public static string bFolderG = "";
        public static string gameFolder = "";

        public static string[] nameList = {
            "autoBackup","autoNaming","popup","namingPattern","backupInGameFolder","backupFolder","gameFolder"
        };
    }

    class SettingPack
    {
        public bool autoBackup = true;
        public bool selfNaming = false;
        public bool popup = false;
        public string namingPattern = "";
        public bool bGameFolder = false;
        public string bFolder = "";
        public SettingPack(bool aB, bool sN, bool pop, string nP, bool gF, string fP)
        {
            autoBackup = aB;
            selfNaming = sN;
            popup = pop;
            namingPattern = (nP == null || nP == string.Empty) ? "" : nP;
            bGameFolder = gF;
            bFolder = (fP == null || fP == string.Empty) ? "" : fP;
        }
        public SettingPack()
        {
            autoBackup = Setting.autoBackupG;
            selfNaming = Setting.selfNamingG;
            popup = Setting.popupG;
            namingPattern = Setting.namingPatternG;
            bGameFolder = Setting.bGameFolderG;
            bFolder = Setting.bFolderG;
        }
    }
}
